package com.shop.order.server.service.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.shop.order.server.dao.OrderDetailDao;
import com.shop.order.server.dao.OrderMasterDao;
import com.shop.order.server.entity.OrderDetail;
import com.shop.order.server.entity.OrderMaster;
import com.shop.order.server.enums.OrderStatusEnum;
import com.shop.order.server.enums.PayStatusEnum;
import com.shop.order.server.service.OrderService;
import com.shop.order.server.util.KeyUtil;
import com.shop.order.server.vo.OrderCreateVo;
import com.shop.product.client.ProductClient;
import com.shop.product.common.ProductInfoOutput;
import com.shop.product.common.ProductInfoVo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

/**
 * Created with IntelliJ IDEA. User: dpengpeng Date: 2018/5/19 Time: 11:45 Description:
 */
@Service
public class OrderServiceImpl implements OrderService {


  private final OrderDetailDao orderDetailDao;

  private final OrderMasterDao orderMasterDao;

  private final ProductClient productClient;

  @Autowired
  public OrderServiceImpl(OrderDetailDao orderDetailDao, OrderMasterDao orderMasterDao, ProductClient productClient) {
    this.orderDetailDao = orderDetailDao;
    this.orderMasterDao = orderMasterDao;
    this.productClient = productClient;
  }

  @Override
  @Transactional
  public String create(OrderCreateVo vo) {

    String orderId = KeyUtil.genUniqueKey();
    //商品信息
    List<ProductInfoVo> productInfoList;
    productInfoList = new Gson().fromJson(vo.getItems(), new TypeToken<List<ProductInfoVo>>() {
    }.getType());
    List<String> productIds = productInfoList.stream().map(ProductInfoVo::getProductId).collect(Collectors.toList());
    List<ProductInfoOutput> productInfoOutputlist = productClient.listForOrder(productIds);

    //总价
    BigDecimal totalMoney = new BigDecimal(BigInteger.ZERO);
    for (ProductInfoOutput productInfoVo : productInfoOutputlist) {
      for (ProductInfoVo infoVo : productInfoList) {
        if (infoVo.getProductId().equals(productInfoVo.getProductId())) {
          //订单详情
          OrderDetail orderDetail = new OrderDetail();
          orderDetail.setDetailId(KeyUtil.genUniqueKey());
          orderDetail.setOrderId(orderId);
          orderDetail.setProductIcon(productInfoVo.getProductIcon());
          orderDetail.setProductId(infoVo.getProductId());
          orderDetail.setProductName(productInfoVo.getProductName());
          orderDetail.setProductPrice(productInfoVo.getProductPrice());
          orderDetail.setProductQuantity(infoVo.getProductQuantity());
          orderDetailDao.save(orderDetail);
          //总价
          totalMoney = totalMoney
              .add(productInfoVo.getProductPrice().multiply(new BigDecimal(infoVo.getProductQuantity())));
        }
      }
    }

    //订单
    OrderMaster orderMaster = new OrderMaster();
    orderMaster.setBuyerAddress(vo.getAddress());
    orderMaster.setBuyerName(vo.getName());
    orderMaster.setBuyerOpenid(vo.getOpenid());
    orderMaster.setBuyerPhone(vo.getPhone());
    orderMaster.setOrderAmount(totalMoney);
    orderMaster.setOrderId(orderId);
    orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
    orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
    Date date = new Date();
    orderMaster.setCreateTime(date);
    orderMaster.setUpdateTime(date);
    orderMasterDao.save(orderMaster);

    //扣库存Buckle stock
    productClient.buckleStock(productInfoList);

    return orderId;
  }

  /**
   * 完成订单
   */
  @Override
  @Transactional
  public void finish(String orderId) {
    //判读订单
    Optional<OrderMaster> optionalOrderMaster = orderMasterDao.findById(orderId);
    if (!optionalOrderMaster.isPresent()) {
      throw new RuntimeException("订单不存在");
    }
    //判断订单状态
    OrderMaster orderMaster = optionalOrderMaster.get();
    if (!orderMaster.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
      throw new RuntimeException("订单状态错误");
    }

    //修改订单状态
    orderMaster.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
    orderMasterDao.save(orderMaster);

    //查询订单详情
    List<OrderDetail> orderDetailList = orderDetailDao.findByOrderId(orderId);
    if (CollectionUtils.isEmpty(orderDetailList)) {
      throw new RuntimeException("订单详情不存在");
    }
  }
}
